package com.interceptor;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.List;

public class AddSoapHeaderInterceptor extends AbstractSoapInterceptor {
    private static String nameURI = "http://localhost:8085/service/schoolMgrService";

    public AddSoapHeaderInterceptor() {
        super(Phase.WRITE);
    }

    public void handleMessage(SoapMessage message) throws Fault {
        String username = "admin";
        String password = DigestUtils.md5Hex("123456");
        QName qname = new QName("RequestSOAPHeader");
        Document doc = DOMUtils.createDocument();

        //自定义节点
        Element usernameElement = doc.createElement("tns:username");
        usernameElement.setTextContent(username);
        Element passwordElement = doc.createElement("tns:password");
        passwordElement.setTextContent(password);

        Element root = doc.createElementNS(nameURI, "tns:RequestSOAPHeader");
        root.appendChild(usernameElement);
        root.appendChild(passwordElement);

        SoapHeader head = new SoapHeader(qname, root);
        List<Header> headers = message.getHeaders();
        headers.add(head);
        System.out.println(">>>>>添加header<<<<<<<");
    }

}